from machine import I2C, Pin import time #################################################################### #This is a class called CAT24C02, which is a library for #interacting with a CAT24C02 EEPROM chip using the I2C protocol. #################################################################### class CAT24C02(object): def __init__(self, i2c, i2c_addr, pages=2, bpp=16): self.i2c = i2c self.i2c_addr = i2c_addr self.pages = pages self.bpp = bpp # bytes per page def capacity(self): """Storage capacity in bytes""" return self.pages * self.bpp def read(self, addr, nbytes): """Read one or more bytes from the EEPROM starting from a specific address""" return self.i2c.readfrom_mem(self.i2c_addr, addr, nbytes, addrsize=8) def write(self, addr, buf): """Write one or more bytes to the EEPROM starting from a specific address""" offset = addr % self.bpp partial = 0 # partial page write if offset > 0: partial = self.bpp - offset self.i2c.writeto_mem(self.i2c_addr, addr, buf[0:partial], addrsize=8) time.sleep_ms(5) addr += partial # full page write for i in range(partial, len(buf), self.bpp): self.i2c.writeto_mem(self.i2c_addr, addr+i-partial, buf[i:i+self.bpp], addrsize=8) time.sleep_ms(5) def wipe(self): buf = b'\xff' * 32 for i in range(1): self.write(i*32, buf) ################################################## #this is the main program following the class ################################################## sda=machine.Pin(16) scl=machine.Pin(17) i2c=machine.I2C(0,sda=sda, scl=scl, freq=400000) i2caddr=80 #Set the I2C address of your EEPROM. #print("I2C Devices :") #print(i2c.scan()) eeprom = CAT24C02(i2c,i2caddr) #create an instance of the class ####################################### #Read and Write routines for the 24c02 ####################################### #eeprom.write(0, b'0123456789BCDEF0123456789abcdef') # Write String to memory address 0 eeprom.write(0, 'Th') # Write String to memory address 0 #eeprom.write(0, b'00000000000000001111111111111111') # Mutliple page writes (fill pages 0 and 1 with test data) #eeprom.write(13, b'abcdef') # Write is performed in two steps, "abc" in the first page then "def" in the next page #eeprom.wipe() # Wipe the EEPROM #print(eeprom.read(0,32)) #read the entire memory space (256 bits, 32 bytes) print(eeprom.read(0,2)) #Read one byte #print((eeprom.read(0, 32)).decode('utf-8')) #Read and print 32Bytes as a string starting from memory address 0 #print((eeprom.read(0, 10)).decode('ascii'))